<template>
  <div>
    <el-card class="box-card">
      <el-row>
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">系统管理</el-breadcrumb-item>
          <el-breadcrumb-item>员工管理</el-breadcrumb-item>
        </el-breadcrumb>
      </el-row>
      <el-row><br><br></el-row>
      <el-row>
        <el-form :inline="true" :model="dto" label-width="100px" class="form-inline" size="small" ref="dtoForm" :rules="dtoRules">
          <el-form-item label="员工姓名" prop="name">
            <el-input v-model="dto.name" placeholder="请输入员工姓名"></el-input>
          </el-form-item>
          <el-form-item label="员工部门" :label-width="formLabelWidth" prop="deptid" >
            <el-select v-model="dto.deptid" filterable placeholder="请选择所在部门" style="width: 100%;">
              <el-option
                v-for="item in departmentList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="员工性别" prop="sex">
            <el-select v-model="dto.sex" clearable placeholder="请选择">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="入职时间" >
            <el-date-picker
              v-model="timeValue"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="工龄≥" prop="workAge">
            <el-input-number v-model="dto.workage" @change="handleChange" :min="0"  label="描述文字"></el-input-number>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-button type="primary" icon="el-icon-search" @click="getEmployeeList()">查询</el-button>
          <el-button type="warning" @click="resetForm('dtoForm')">清空</el-button>
          <el-button type="success" round @click="handleAdd()">添加员工</el-button>
        </el-col>
      </el-row>
      <el-row><br><br></el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="22">
          <el-table
            :data="employeeList"
            style="width: 100%">
            <el-table-column
              label="序号"
              type="index"
              width="50">
            </el-table-column>
            <el-table-column
              prop="name"
              label="员工姓名"
              width="80">
            </el-table-column>
            <el-table-column
              prop="workage"
              label="工龄"
              width="60">
            </el-table-column>
            <el-table-column
              prop="age"
              label="员工年龄"
              width="80">
            </el-table-column>
            <el-table-column
              prop="sex"
              label="性别"
              width="60">
            </el-table-column>
            <el-table-column
              prop="salary"
              label="员工薪水(元)"
              width="100">
            </el-table-column>
            <el-table-column
              prop="department.name"
              label="员工部门"
              width="100">
            </el-table-column>
            <el-table-column
              label="状态"
              width="60">
              <template slot-scope="scope">
                <span style="color: green;" v-if="scope.row.status == 1">启用</span>
                <span style="color: red;" v-else>冻结</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="birthday"
              label="员工生日"
              width="100"
              :formatter="formatDateToYMD">
            </el-table-column>
            <el-table-column
              prop="inductiontime"
              label="入职日期"
              width="100"
              :formatter="formatDateToYMD">
            </el-table-column>
            <el-table-column label="操作" width="300" fixed="right">
              <template slot-scope="scope">
                <el-button
                  size="mini" type="primary" icon="el-icon-edit"
                  @click="handleEdit(scope.row)">编辑</el-button>
                <el-button
                  size="mini" v-if="scope.row.status == 1" type="warning"
                  @click="handleDisable(scope.row)">冻结</el-button>
                <el-button
                  size="mini" v-if="scope.row.status == 0" type="success"
                  @click="handleEnable(scope.row)">启用</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.row)">开除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="1"><br></el-col>
        <el-col :span="5">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="dto.page"
            :page-size="dto.size"
            layout="total, prev, pager, next"
            :total="total">
          </el-pagination>
        </el-col>
      </el-row>
    </el-card>
     <!-- 表单弹出框 -->
     <el-dialog :title="formtitle" :visible.sync="dialogEmployeeVisible" width="30%" @close="close('ruleForm')">
      <el-form :model="employee" :rules="currentRules" ref="ruleForm">
        <el-form-item label="员工姓名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="employee.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="账号" :label-width="formLabelWidth" prop="account">
          <el-input v-model="employee.account" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input type="password" v-model="employee.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth" prop="checkPass">
          <el-input type="password" v-model="employee.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工部门" :label-width="formLabelWidth" prop="deptid" >
          <el-select v-model="employee.deptid" filterable placeholder="请选择所在部门" style="width: 100%;">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工薪水" :label-width="formLabelWidth" prop="salary">
          <el-input v-model="employee.salary" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工性别" :label-width="formLabelWidth" prop="sex">
          <el-select v-model="employee.sex" placeholder="请选择" style="width: 100%;">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间" :label-width="formLabelWidth" prop="inductiontime">
          <el-date-picker type="date" placeholder="选择日期" v-model="employee.inductiontime" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="{ disabledDate(time) { return time > new Date(); } }"></el-date-picker>
        </el-form-item>
        <el-form-item label="生日日期" :label-width="formLabelWidth" prop="inductiontime">
          <el-date-picker type="date" placeholder="选择日期" v-model="employee.birthday" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="{ disabledDate(time) { return time > new Date(); } }"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="handleConfirm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var checkAccount = (rule, value, callback) => {
      if (this.formtitle == '编辑员工' && this.employee.account == '') {
        callback();
      } else {
        this.$axios.get("/user/checkAccount/" + this.employee.account).then(res=>{
        if (res.data.code == 200) {
          if (res.data.data) {
            callback();
          } else {
            callback(new Error('该账号已存在'));
          }
        }
      })
      }
    };
    var checkPass = (rule, value, callback) => {
      if(this.employee.password != '' && this.employee.checkPass != '' && this.employee.password != this.employee.checkPass){
        callback(new Error('两次密码不一致'));
      } else {
        callback();
      }
    };
    var validateAtLeastOneChange = (rule, value, callback) => {
      if (this.employee.account == '' && this.employee.password =='' && this.employee.name == this.oldEmployee.name && this.employee.deptid == this.oldEmployee.deptid && this.employee.inductiontime == this.oldEmployee.inductiontime && this.employee.salary == this.oldEmployee.salary && this.employee.birthday == this.oldEmployee.birthday && this.employee.sex == this.oldEmployee.sex) {
        callback(new Error('请至少修改一项数据'));
      } else{
        callback();
      }
    }
    return {
      dto: {
        id: '',
        name: '',
        deptid:'',
        workage:'',
        sex:'',
        startTime:'',
        endTime:'',
        page: 1,
        size: 5
      },
      timeValue: '',
      total: 0,
      employeeList: [],
      departmentList: [],
      dialogEmployeeVisible: false,
      formtitle: '',
      formLabelWidth: '80px',
      employee: {
        id: '',
        account:'',
        password:'',
        checkPass:'',
        name: '',
        deptid: '',
        inductiontime: '',
        salary: '',
        birthday: '',
        sex: '',
      },
      oldEmployee: {
        id: '',
        account:'',
        password:'',
        checkPass:'',
        name: '',
        deptid: '',
        inductiontime: '',
        salary: '',
        birthday: '',
        sex: '',
      },
      currentRules:{},
      ruleAdd:{
        name: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' },
        ],
        account: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' },
          { validator:checkAccount, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator:checkPass, trigger: 'blur' }
        ],
        checkPass: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator:checkPass, trigger: 'blur' }
        ],
        deptid: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        salary: [
          { required: true, message: '请输入薪水', trigger: 'blur' },
          { 
            pattern: /^(0+(\.\d{1,2})?|([1-9]\d*(\.\d{1,2})?))$/, 
            message: '薪资必须是最多带有两位小数的数字',
            trigger: 'blur'
          }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        inductiontime: [
          { required: true, message: '请选择入职时间', trigger: 'change' }
        ],
        birthday: [
          { required: true, message: '请选择生日日期', trigger: 'change' }
        ]
      },
      ruleEdit:{
        name: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' },
          { validator: validateAtLeastOneChange, trigger: 'blur' }
        ],
        account: [
          { validator:checkAccount, trigger: 'blur' },
          { validator: validateAtLeastOneChange, trigger: 'blur' }
        ],
        password: [
          { validator:checkPass, trigger: 'blur' },
          { validator: validateAtLeastOneChange, trigger: 'blur' }
        ],
        checkPass: [
          { validator:checkPass, trigger: 'blur' },
          { validator: validateAtLeastOneChange, trigger: 'blur' }
        ],
        deptid: [
          { required: true, message: '请选择部门', trigger: 'change' },
          { validator: validateAtLeastOneChange, trigger: 'change' }
        ],
        salary: [
          { required: true, message: '请输入薪水', trigger: 'blur' },
          { 
            pattern: /^(0+(\.\d{1,2})?|([1-9]\d*(\.\d{1,2})?))$/, 
            message: '薪资必须是最多带有两位小数的数字',
            trigger: 'blur'
          },
          { validator: validateAtLeastOneChange, trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' },
          { validator: validateAtLeastOneChange, trigger: 'change' }
        ],
        inductiontime: [
          { required: true, message: '请选择入职时间', trigger: 'change' },
          { validator: validateAtLeastOneChange, trigger: 'change' }
        ],
        birthday: [
          { required: true, message: '请选择生日日期', trigger: 'change' },
          { validator: validateAtLeastOneChange, trigger: 'change' }
        ]
      },
    }
  },
  watch:{
     // 监听title的变化，动态切换规则集
     formtitle(newTitle) {
      this.currentRules = newTitle === '添加员工' ? this.ruleAdd : this.ruleEdit;
      // 如果需要，可以在这里触发表单的重新验证
      // this.$refs.ruleForm.validate();
    }
  },
  mounted() {
    this.getEmployeeList()
    this.getDepartmentList()
  },
  methods:{
    handleCurrentChange(val){
      this.dto.page = val
      this.getDepartmentList()
    },
    //重置查询表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.timeValue = ''
      this.dto.workage = 0
    },
    getDepartmentList(){
      this.$axios.get('/department/getAllDepartment').then(res=>{
        this.departmentList = res.data.data
      })
    },
    getEmployeeList(){
      this.dto.startTime = this.timeValue[0]
      this.dto.endTime = this.timeValue[1]
      this.$axios.get('/employee/getEmployeeList',{
        params:this.dto
      }).then(res=>{
        this.employeeList = res.data.data.data
        this.total = res.data.data.total
      })
    },
    formatDateToYMD(row, column, value) {
      // 如果value是有效的日期时间字符串，可以使用以下方式直接格式化
      if (value) {
        const date = new Date(value);
        const year = date.getFullYear();
        const month = this.padZero(date.getMonth() + 1); // 月份是从0开始的，所以加1
        const day = this.padZero(date.getDate());
        return `${year}-${month}-${day}`;
      }
      return '';
    },
    padZero(num) {
      return num < 10 ? '0' + num : num; // 用于补零操作，保证日期格式为两位数
    },
    close(formName){
      this.$refs[formName].clearValidate();
      this.dialogEmployeeVisible = false
    },
    handleAdd(){
      this.dialogEmployeeVisible = true
      this.formtitle = "添加员工"
      this.employee = {
        id: '',
        account:'',
        password:'',
        checkPass:'',
        name: '',
        deptid: '',
        inductiontime: '',
        salary: '',
        birthday: '',
        sex: '',
      }
    },
    handleEdit(row){
      this.dialogEmployeeVisible = true
      this.formtitle = "编辑员工"
      this.oldEmployee = row
      this.employee = {
        id: row.id,
        account:'',
        password:'',
        checkPass:'',
        name: row.name,
        deptid: row.deptid,
        inductiontime: row.inductiontime,
        salary: row.salary,
        birthday: row.birthday,
        sex: row.sex,
      }
      console.log(this.oldEmployee)
    },
    handleConfirm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = {
              id: this.employee.id,
              name: this.employee.name,
              deptid: this.employee.deptid,
              inductiontime: this.employee.inductiontime,
              salary: this.employee.salary,
              birthday: this.employee.birthday,
              sex: this.employee.sex,
              user:{
                account: this.employee.account,
                pass: this.employee.password
              }
            }
          if (this.formtitle == '添加员工') {
            this.$axios.post('/employee/addEmployee',data).then(res=>{
              if (res.data.code == 200) {
                this.$message({
                  message: '添加成功！',
                  type: 'success'
                });
                this.dialogEmployeeVisible = false
                this.getEmployeeList()
              }
            })
          }
          if (this.formtitle == '编辑员工') {
            if (this.employee.name != this.oldEmployee.name) {
              data.isNameUpdate = 1
            } else {
              data.isNameUpdate = 0
            }
            this.$axios.put('/employee/editEmployee',data).then(res=>{
              if (res.data.code == 200) {
                this.$message({
                  message: '编辑成功！',
                  type: 'success'
                });
                this.dialogEmployeeVisible = false
                this.getEmployeeList()
              }
            })
          }     
        } else {
          return false;
        }
      }); 
    },
    handleEnable(row){
      this.$axios.put('/employee/enableEmployee/' + row.id).then(res=>{
        if (res.data.code == 200) {
          this.$message({
            type: 'success',
            message: '启用成功!'
          });
          this.getEmployeeList()
        }
      })
    },
    handleDisable(row){
      this.$axios.put('/employee/disableEmployee/' + row.id).then(res=>{
        if (res.data.code == 200) {
          if (res.data.data) {
            this.$message({
              type: 'success',
              message: '停用成功!'
            });
            this.getEmployeeList()
          }        
        }
      })
    },
    handleDelete(row){
      this.$confirm('此操作将永久开除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete('/employee/deleteEmployee/' + row.id).then(res=>{
          if (res.data.code == 200) {
            if (res.data.data){
              this.$message({
                type: 'success',
                message: '开除成功!'
              });
              this.getEmployeeList()
            }
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消开除'
        });          
      });
    }
  }
}
</script>

<style scoped>

</style>